package com.liunian.discovery.impl;

import com.liunian.Constant;
import com.liunian.ServiceConfig;
import com.liunian.discovery.AbstractRegistry;
import com.liunian.utils.NetUtils;
import com.liunian.utils.zookeeper.ZookeeperNode;
import com.liunian.utils.zookeeper.ZookeeperUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooKeeper;

import java.net.InetSocketAddress;
import java.util.List;

@Slf4j
public class NacosRegistry extends AbstractRegistry {

    private ZooKeeper zookeeper;

    public NacosRegistry() {
        this.zookeeper = ZookeeperUtils.createZookeeper();
    }

    public NacosRegistry(String connectString, int timeOut) {
        this.zookeeper = ZookeeperUtils.createZookeeper(connectString, timeOut);
    }

    @Override
    public void register(ServiceConfig<?> service) {
        // 服务名称的节点
        // 这个节点应该是一个持久节点
        String parentNode = Constant.BASE_PROVIDERS_PATH + "/" + service.getInterface().getName();
        // 如果节点不存在就创建
        if (!ZookeeperUtils.exists(zookeeper, parentNode, null)) {
            ZookeeperNode zookeeperNode = new ZookeeperNode(parentNode, null);
            ZookeeperUtils.createNode(zookeeper, zookeeperNode, null, CreateMode.PERSISTENT);
        }
        // 创建本机的临时节点，ip:port，
        // 服务提供方的端口一般自己设定，但是我们还需要一个获取IP的方法
        // IP我们通常是需要一个局域网IP，不是127.0.0.1这样的，也不是IPv6这种
        // 像这种192.168.12.12
        // todo:
        String node = parentNode + "/" + NetUtils.getIp() + ":" + 8088;
        if (!ZookeeperUtils.exists(zookeeper, node, null)) {
            ZookeeperNode zookeeperNode = new ZookeeperNode(node, null);
            ZookeeperUtils.createNode(zookeeper, zookeeperNode, null, CreateMode.EPHEMERAL);
        }
        if (log.isDebugEnabled()) {
            log.debug("服务：{},已经被注册", service.getInterface().getName());
        }
    }

    @Override
    public List<InetSocketAddress> lookup(String ServiceName, String gruop) {
        return null;
    }
}
